package com.mdinfo.gw.door.driver.aopu;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Created by Administrator on 2018/1/31.
 */
public class AopuDoorHandlerAdapter extends ChannelInboundHandlerAdapter {

    private AopuClient client;
    private AopuReadOpration readOpration;
    private Logger logger = LoggerFactory.getLogger(AopuDoorHandlerAdapter.class);

    public AopuDoorHandlerAdapter(AopuClient client,AopuReadOpration readOpration){
        this.client = client;
        this.readOpration = readOpration;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接成功...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接断开");
        client.doConn();
    }

    /**
     * 读取数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        readOpration.execute(ctx,req);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("出现异常:"+cause.getMessage());
        ctx.close();
    }
}
